package com.saifan.wyy_ov.ui.property;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.RequestBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IViewOnClick;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DateTimePickUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import java.io.File;
import java.util.Date;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-26 13:10:29
 * @descrption 访客管理
 */

public class VisitorManageActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private Toolbar toolbar;
    private EditText contacts;
    private EditText tel;
    private EditText date;
    private EditText timer;
    private CheckBox all;
    private static final int CHOSE_CONTACTS = 1212;
    RequestBean requestBean;
    RoomInfoBean roomInfoBean;
    String YSCS = "";
    private ImageView imageViewdate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestBean = new RequestBean();
        roomInfoBean = getRoomInfoBean();
        setContentView();
        test();
    }

    public void setContentView() {
        setContentView(R.layout.activity_visitor_manage);
        this.imageViewdate = (ImageView) findViewById(R.id.imageView_date);
        this.all = (CheckBox) findViewById(R.id.all);
        this.timer = (EditText) findViewById(R.id.timer);
        this.date = (EditText) findViewById(R.id.date);
        this.tel = (EditText) findViewById(R.id.tel);
        this.contacts = (EditText) findViewById(R.id.contacts);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        all.setOnCheckedChangeListener(this);

    }

    public void test() {
    }

    public void cancel(View view) {
        finish();

    }

    public void generate(View view) {
        if (roomInfoBean.equals(null)) {
            return;
        }

        if (isEmpty(contacts)) {
            contacts.setFocusable(true);
            ToastUtil.showToast(this, "请输入联系人");
            return;
        }
        if (isEmpty(tel)) {
            tel.setFocusable(true);
            ToastUtil.showToast(this, "请输入电话");
            return;
        }
        if (!StringUtil.checkPhoneNum(tel.getText().toString())) {
            tel.setFocusable(true);
            ToastUtil.showToast(this, "请输入正确的电话");
            return;
        }
        if (isEmpty(date)) {
            specialDate(imageViewdate);
            ToastUtil.showToast(this, "请输入有效期");
            return;
        }
        if (all.isChecked()) {
            requestBean.setFKGL_YXCS(99999);
            requestBean.setFKGL_SYCS(99999);
        } else {
            if (isEmpty(timer)) {
                ToastUtil.showToast(this, "请输入次数 或选择不限");
                return;
            }
            if (timer.getText().toString().startsWith("0")) {
                timer.setError("请输入( >0 )的有效的次数");
                ToastUtil.showToast(this, "请输入( >0 )的有效的次数");
                return;
            }
            requestBean.setFKGL_SYCS(Integer.valueOf(timer.getText().toString().trim()));
            requestBean.setFKGL_YXCS(Integer.valueOf(timer.getText().toString().trim()));
        }
        requestBean.setXMBS(roomInfoBean.getXMBS());
        requestBean.setFKGL_WYFKGXWJ(roomInfoBean.getFKGX_ZJ());
        requestBean.setFKGL_LFR(contacts.getText().toString().trim());
        requestBean.setFKGL_LFRDH(tel.getText().toString().trim());
        requestBean.setFKGL_YXSJ(date.getText().toString());

        GetData getData = new GetData();
        getData.getDataJson(this, Api.Customer.VISITOR, requestBean, getString(R.string.wait), new ResponseData() {
            @Override
            public void onSuccess(String json) {
                if (!StringUtil.isNullOrEmpty(json)) {
                    Intent intent = new Intent(VisitorManageActivity.this, GenerateQRActivity.class);
                    String s = json.substring(2, 22);
                    intent.putExtra("qr", json.substring(2, 22));
                    intent.putExtra("timer", requestBean.getFKGL_YXCS() + "");
                    intent.putExtra("contacts", contacts.getText().toString().trim());
                    intent.putExtra("tel", tel.getText().toString().trim());
                    intent.putExtra("date", date.getText().toString().trim().substring(0, 10));
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailed(String str) {


            }
        });


    }


    public void specialDate(View view) {
        DateTimePickUtils.show(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {
                date.setText(object[0].toString());
            }
        }, new Date());
    }

    public void getContacts(View view) {


        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, CHOSE_CONTACTS);
                return;
            } else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, CHOSE_CONTACTS);

            }
        } else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, CHOSE_CONTACTS);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CHOSE_CONTACTS:
                if (!(resultCode == RESULT_OK)) {
                    return;
                }
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                String name = "";
                String number = "";
                try {


                    Cursor cursor = getContentResolver().query(uri, null, null, null,
                            null);
                    if (cursor != null && cursor.moveToFirst()) {

                        int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                        name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                            if (phones.moveToFirst()) {
                                //
                                number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            }
                        }
                        cursor.close();
                        tel.setText(number.replace(" ",""));
                        contacts.setText(name);
                    }
                } catch (Exception e) {
                    LogUtil.e(e.toString());
                }

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public boolean isEmpty(TextView view) {
        return view.getText().toString().trim().isEmpty();
    }

    int temp = 1;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked) {
            if (!timer.getText().toString().trim().isEmpty()) {
                temp = Integer.valueOf(timer.getText().toString());
            } else {
                temp = 1;
            }


            requestBean.setFKGL_YXCS(99999);
            requestBean.setFKGL_SYCS(99999);
            timer.setEnabled(false);

        } else {

            timer.setText(temp + "");
            requestBean.setFKGL_YXCS(temp);
            requestBean.setFKGL_SYCS(temp);
            timer.setEnabled(true);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
         if (requestCode==CHOSE_CONTACTS){

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, CHOSE_CONTACTS);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }
}
